#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import traceback

from Ump import utils
from  Ump.objs.session_wrapper import _sw
from Ump.common import  log
from Ump.common import exception
from Ump.objs.manager_base import Manager
from Ump.objs.volume.manager import VolumeManager
from Ump.objs.db import models
from Ump.objs.session_wrapper import enable_log_and_session


LOG = log.get_log('Ump.objs.access_policy.manager')


def add(x,y):
    return x + y


@models.add_model(models.AccessPolicy)
class AccessPolicyManager(Manager):

    def __init__(self):
        self.super_ = super(AccessPolicyManager, self)
        self.super_.__init__()
        self.vom = VolumeManager()
        
    def _check_double_name(self, user_id, name):
        qoses = _sw.get_one(model=models.AccessPolicy, id_or_spec={'user_id': user_id, 'name': name})
        if qoses:
            raise Exception("指定的名称已被使用")

    @enable_log_and_session(resource='access_control', event='create')
    def create(self, _logger, kwargs):
        name = kwargs['name']
        _logger.update_props(oplog_obj=name)

        policy = self._create(**kwargs)
        return policy

    def _create(self, name, iprange=None, initiatorName=None, username='admin', **kwargs):

        user_id = _sw.get_user_id(username),
        self._check_double_name(user_id, name)

        values = {
            'user_id': user_id,
            'name': name,
            'iprange': iprange,
            'initiatorName': initiatorName,
        }
        
        policy = models.AccessPolicy(values).save()
        return policy 

    @enable_log_and_session(resource='access_control', event='delete')
    def delete(self, _logger, kwargs):
        policy_id = kwargs.get('id')
        policy = self._get_one(policy_id)

        _logger.update_props(oplog_obj=policy.name)

        if policy.volumes:
            raise Exception("访问策略(%s)已经被卷使用，不可删除" % (policy.name))
        return policy.delete()

    def _get_one(self, policy_id):
        policy = _sw.get_one(models.AccessPolicy, id_or_spec=policy_id)
        if not policy:
            raise exception.NotFound(policy_id=policy_id)
        return policy

    @enable_log_and_session(resource='access_control', event='update')
    def update(self, _logger, kwargs):
        policy_id = kwargs.get('id')
        policy = self._get_one(policy_id)

        _logger.update_props(oplog_obj=policy.name)

        policy = self._update(policy, **kwargs)
        return policy

    def _update(self, policy, name=None, iprange=None, initiatorName=None, cluster_id=1, **kwargs): 
        # user_id = _sw.get_user_id(kwargs.get('username'))
        if policy.name != name: 
            self._check_double_name(policy.user_id, name)

        values = dict()
        utils.update_values(values, 'name', name)
        utils.update_values(values, 'iprange', iprange)
        utils.update_values(values, 'initiatorName', initiatorName)
    
        policy.update(values)

        volumes = _sw.get_list(models.Volume, spec={'access_policy_id':policy.id})
        for volume in volumes: 
            self.vom._update(volume, access_policy_id=volume.access_policy.id)
        return policy
